﻿using Ef.Core.Imp.Entity;
using Microsoft.EntityFrameworkCore;

namespace Ef.Core.Imp
{
    /// <summary>
    /// 自定义 数据上下文
    /// </summary>
    public class MyDbContext : DbContext
    {
        public DbSet<TestTable> TestTables { get; set; }

        public DbSet<TestTableRelation> TestTableRelation { get; set; }

        public DbSet<TestTableDetail> TestTableDetails { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseLazyLoadingProxies();
            //写入连接字符串
            optionsBuilder.UseSqlServer("Data Source=.\\SQLSERVER;Initial Catalog=EfCore.Test;User ID=sa;Pwd=123");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // 映射实体关系，一对多
            modelBuilder.Entity<TestTableDetail>()
                        .HasOne(p => p.Test)
                        .WithMany(p => p.TestTableDetails)
                        .HasForeignKey(p => p.PID);
            // 映射实体关系，一对一          
            modelBuilder.Entity<TestTable>()
                       .HasOne(b => b.TestTableRelation)
                       .WithOne()
                       .HasForeignKey<TestTableRelation>(b => b.PID);
        }     
    }
}
